// pages/present/lindex.js
import axios from "../network/index"
import areaList from '../../utils/area.js'
import {
  fileUrl
} from "../network/index"
let app = getApp()
let timer
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showCity: false,
    areaList: {},
    cityCode: '',
    cityName: "",
    code: "",
    userId: "",
    modal: false, //上传图片弹出
    filetype: "1", //上传文件的类型 是发票，还是材料
    unfold: false,
    materials: {},
    memo: '', //备注
    currentMaterials: "",
    projectData: "",
    seletctMaterialsStatus: false,
    currentV: {},
    number: 0,
    totalPrice: 0,
    taskNumber: [],
    billPicture: [],
    inventoryPicture: [],
    type: "",
  },
  cancel() {
    this.setData({
      modal: false,
    })
  },
  modal(e) {

    let type = e.currentTarget.dataset.type
    this.setData({
      modal: true,
      type
    })
  },
  //计算总金额
  sumPrice() {
    let totalPrice = 0
    let taskNumber = this.data.taskNumber
    taskNumber.forEach(v => {
      if (v.price == '') {

      } else {
        totalPrice += parseFloat(v.price)
      }

    })
    this.setData({
      totalPrice
    })
  },
  //备注
  memoIpt(e) {
    this.setData({
      memo: e.detail.value
    })
  },
  //获取单价的值
  price(e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    //  let value = this.validateNumber(e.detail.value)
    let value = e.detail.value
    let taskNumber = this.data.taskNumber
    taskNumber[index].unitPrice = value
    taskNumber[index].price = (value * taskNumber[index].number).toFixed(2)
    this.sumPrice()
    this.setData({
      taskNumber
    })
  },
  //只能输入数字
  validateNumber(e) {
    console.log(1)
    return e.replace(/[\D\.]/g, '')
  },
  //选择材料状态
  confirmMaterials(e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index

    let taskNumber = this.data.taskNumber
    taskNumber[index].seletctMaterialsStatus = !taskNumber[index].seletctMaterialsStatus
    this.setData({
      taskNumber,

    })
  },
  confirmSelect() {
    this.setData({
      unfold: !this.data.unfold
    })
  },
  //数量加减
  handelNumberAdd(e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    let taskNumber = this.data.taskNumber
    if (taskNumber[index].selectMaterialsValue == '') {
      wx.showToast({
        title: '请先选择报销材料',
        icon: "none"
      })
      return
    }
    console.log(taskNumber[index], 'taskNumber[index]');

    taskNumber[index].number++
    let defaultPrice = taskNumber[index].unitPrice
    let count = taskNumber[index].number
    taskNumber[index].price = (count * defaultPrice).toFixed(2)
    this.setData({
      taskNumber,
    })
    this.sumPrice()
  },
  //数量加减
  handelNumberMinus(e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    let taskNumber = this.data.taskNumber
    let defaultPrice = taskNumber[index].unitPrice
    if (taskNumber[index].selectMaterialsValue == '') {
      wx.showToast({
        title: '请先选择报销材料',
        icon: "none"
      })
      return
    }
    if (taskNumber[index].number < 2) {
      return
    } else {
      taskNumber[index].number--
    }

    let count = taskNumber[index].number
    taskNumber[index].price = count * defaultPrice
    this.sumPrice()
    this.setData({
      taskNumber,
    })
  },
  //数量加减结束
  // 添加任务
  addTask() {
    let taskNumber = this.data.taskNumber
    let field = JSON.stringify(taskNumber[0])
    let parseField = JSON.parse(field)
    parseField.number = 1
    parseField.price = 0
    parseField.unitPrice = 0
    parseField.selectMaterialsLable = ''
    parseField.selectMaterialsValue = ''
    parseField.firstchoice = false
    taskNumber.push(parseField)
    this.setData({
      taskNumber
    })
  },
  //输入数量
  numberClick(e) {
    let currentTaskIndex = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber

    let number = e.detail.value

    let currentPrice = number * taskNumber[currentTaskIndex].unitPrice
    taskNumber[currentTaskIndex].price = currentPrice.toFixed(2)
    taskNumber[currentTaskIndex].number = number
    this.sumPrice()
    this.setData({
      taskNumber,
    })
  },
  getProject(val) {
    axios({
      url: "/api/reimbursed/getProjecAllData",
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        searchVal: val
      }
    }).then(v => {

      this.setData({
        projectData: v.data
      })
    })
  },
  //获取材料
  getMaterials(v) {

    axios({
      url: "/api/reimbursed/getMaterialAllData",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: {
        searchVal: v
      }
    }).then(v => {

      // let taskNumber=this.data.taskNumber
      // taskNumber[0].unitPrice=parseInt(v.data[0].materialDefaultAmout)
      // taskNumber[0].price=parseInt(v.data[0].materialDefaultAmout)
      // taskNumber[0].selectMaterialsLable=v.data[0].materialName
      // taskNumber[0].selectMaterialsValue=v.data[0].materialCode

      this.setData({
        materials: v.data,
        // taskNumber
      })
    }).catch(V => {

      wx.showToast({
        title: V,
      })
    })
  },
  //项目下拉获取选中  的值
  currentValue(e) {

    this.setData({
      currentV: e.currentTarget.dataset,
      unfold: false
    })
  },
  //删除该任务
  delTask(e) {
    let _this = this
    let currentDelTask = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    if (currentDelTask == 0) {
      wx.showToast({
        title: '该任务不允许删除',
        icon: "none"
      })
      return
    } else {
      wx.showModal({
        title: '提示',
        content: "是否删除该任务",
        success(res) {
          if (res.confirm) {
            wx.showToast({
              title: '删除成功',
            })
            _this.sumPrice()
            let newtaskNumber = taskNumber.filter((item, index) => {

              return (currentDelTask != index)
            })
            _this.sumPrice()
            _this.setData({
              taskNumber: newtaskNumber
            })

          } else {
            wx.showToast({
              title: '取消删除',
              icon: "none"
            })
          }
        }
      })

    }
  },
  //项目搜索的值
  searchProject(e) {
    let v = e.detail.value
    clearTimeout(timer)
    timer = setTimeout(() => {
      this.getProject(v)
      this.setData({
        unfold: true
      })
    }, 10)


  },
  //搜素材料
  searchMaterials(e) {
    let v = e.detail.value
    let i = e.currentTarget.dataset.index
    // let taskNumber=this.data.taskNumber
    clearTimeout(timer)
    timer = setTimeout(() => {
      let set = `taskNumber[${i}].seletctMaterialsStatus`
      this.getMaterials(v)
      this.setData({
        [set]: true
      })
    }, 10);
  },
  //选择材料
  currentMaterialsV(e) {
    let taskNumber = this.data.taskNumber
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    let lable = dataset.v
    let code = dataset.key
    let price = dataset.defalutprice
    taskNumber[index].selectMaterialsLable = lable
    taskNumber[index].selectMaterialsValue = code
    taskNumber[index].price = price
    taskNumber[index].number = 1
    taskNumber[index].seletctMaterialsStatus = false,
      taskNumber[index].unitPrice = price
    this.sumPrice()
    this.setData({
      taskNumber
    })
  },
  //删除图
  delPicture(e) {
    //获取图片的下标
    let {
      index,
      type
    } = e.currentTarget.dataset
    let _this = this
    wx.showModal({
      title: "提示",
      content: "是否删除图片",
      success(res) {
        if (res.confirm) {
          if (type == "1") {
            let billPicture = _this.data.billPicture.filter((item, i) => {
              return !(index == i)
            })
            _this.setData({
              billPicture
            })

          } else {
            let inventoryPicture = _this.data.inventoryPicture.filter((item, i) => {
              return !(index == i)
            })
            _this.setData({
              inventoryPicture
            })
          }
          wx.showToast({
            title: '删除成功',
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '取消删除',
            icon: "none"
          })
        }
      }
    })

  },

  //上传文件
  uploadFile() {
    this.setData({
      modal: false
    })
    let type = this.data.type
    let _this = this
    let billPicture = this.data.billPicture
    let inventoryPicture = this.data.inventoryPicture
    wx.chooseMessageFile({
      type: "all",
      count: 10,
      extension: app.globalData.extension,
      success: (v) => {
        wx.showLoading({
          title: '文件上传中...',
        })

        v.tempFiles.forEach(item => {
          let suffixArray = item.name.split('.')
          let suffix = suffixArray[suffixArray.length - 1]
          wx.uploadFile({
            filePath: item.path,
            name: 'img',
            url: fileUrl,
            success: (v) => {
              wx.hideLoading({
                success: (res) => {},
              })
              if (v.statusCode != 200) {
                wx.showToast({
                  title: '文件上传失败！',
                  icon: "none"
                })
                return
              }
              let file = JSON.parse(v.data).data
              if (type == "1") {
                inventoryPicture.push({
                  url: file,
                  type: 1,
                  fileType: suffix
                })

              } else {
                billPicture.push({
                  url: file,
                  type: 2,
                  fileType: suffix
                })
              }
              _this.setData({
                billPicture,
                modal: false,
                inventoryPicture
              })


            }
          })
        })
      }
    })

  },

  //上传图片
  pricture(e) {

    let index = e.currentTarget.dataset.index
    let type = this.data.type
    let _this = this
    let taskNumber = this.data.taskNumber
    let billPicture = this.data.billPicture
    let inventoryPicture = this.data.inventoryPicture
    //保存本地预览图


    wx.chooseImage({
      count: 10,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],

      complete(e) {
        console.log(e, 555555)
      },
      success(res) {

        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles
        //获取文件大小
        let ratio = 80
        tempFilePaths.forEach(element => {
          if (element.size > 20971520) {
            wx.showToast({
              title: '图片限制为20M',
              icon: "none"
            })
            return
          } else if (element.size > 10485760)
            ratio = 10
          else if (element.size > 5242880 && element.size < 10485760) {
            ratio = 20
          }
          //压缩图片，只能在真机上使用，模拟器不支持

          wx.compressImage({
            src: element.path,
            quality: ratio,
            success: function (res) {

              wx.showLoading({
                title: '图片上传中...',
              })
              wx.uploadFile({
                filePath: res.tempFilePath,
                name: 'img',
                url: fileUrl,
                success: function (v) {
                  wx.hideLoading({
                    success: (res) => {},
                  })

                  if (v.statusCode != 200) {
                    wx.showToast({
                      title: '图片上传失败',
                      icon: "none"
                    })
                    return
                  }
                  let imageUrl = JSON.parse(v.data).data

                  // taskNumber[index].image.push(imageUrl)

                  // _this.setData({
                  //   taskNumber
                  // })

                  if (type == "1") {
                    inventoryPicture.push({
                      url: imageUrl,
                      type: 1,
                      fileType: 'image'
                    })

                  } else {
                    billPicture.push({
                      url: imageUrl,
                      type: 2,
                      fileType: 'image'
                    })

                  }
                  _this.setData({
                    billPicture,
                    modal: false,
                    inventoryPicture
                  })
                },
                fail: function () {
                  wx.showToast({
                    title: '图片上传失败',
                    icon: "none"
                  })
                }
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '图片压缩失败',
                icon: "none"
              })
            }
          })
        })
      },
      fail: function (v) {
        console.log(v, '失败')
        wx.showToast({
          title: '打开相机失败',
          icon: "none"
        })
      }
    })
  },
  preview(e) {
    // 预览图片
    //该任务的下标

    let type = e.currentTarget.dataset.type
    let previewUrl = e.currentTarget.dataset.image.url
    let file = e.currentTarget.dataset.image.fileType
    if (file != 'image') {
      wx.showLoading({
        title: '正在打开文件',
      })
      wx.downloadFile({
        url: previewUrl,
        success: (res) => {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              wx.hideLoading({
                success: (res) => {},
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '打开文件失败，请重试 ',
                icon: "none"
              })
            }
          })
        }
      })
    } else {
      let urls = this.data.inventoryPicture
      if (type == 1) {
        urls = this.data.billPicture
      }

      let urlsDate = urls.map(v => {
        return v.url
      })
      wx.previewImage({
        current: previewUrl,
        urls: urlsDate
      })
    }
  },
  move() {},
  //提交报销
  submitTask() {
    let taskNumber = this.data.taskNumber
    console.log(this.data.currentV)
    if (Object.keys(this.data.currentV).length == 0) {
      wx.showToast({
        title: "项目不能为空",
        icon: "none"
      })
      return
    }
    if (!this.data.cityName) {
      wx.showToast({
        title: "请选择城市",
        icon: "none"
      })
      return
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    let materialData = taskNumber.map(v => {
      return {
        materialAmout: v.price,
        materialCode: v.selectMaterialsValue,
        materialNum: v.number
      }
    })
    // if(this.data.billPicture.length<1||this.data.inventoryPicture.length<1){
    //   wx.showToast({
    //     title: '请上传相关图片材料',
    //   })
    //   return
    // }
    axios({
      url: "/api/reimbursed/submit",
      method: 'POST',
      data: {
        imgData: [...this.data.billPicture, ...this.data.inventoryPicture],
        materialData,
        projectCode: this.data.currentV.key,
        userId: this.data.userId,
        reimbursedCode: this.data.code,
        cityCode: this.data.cityCode,
        cityName: this.data.cityName,
        memo: this.data.memo
      },

    }, 'application/json').then(v => {
      wx.hideLoading()
      if (v.code == 200) {
        wx.removeStorageSync('detail')
        wx.showToast({
          title: "修改成功",
        })
        wx.switchTab({
          url: '/pages/detail/lindex',
        })

      } else {
        wx.showToast({
          title: v.msg,
        })
      }
    }).catch(v => {
      wx.hideLoading()
      wx.showToast({
        title: v,
      })
    })
  },
  onLoad: function () {
    this.setData({
      areaList
    })
    let userId = wx.getStorageSync('userId')
    let detail = wx.getStorageSync('detail')
    let taskNumber = []
    if (detail) {
      let pro = {
        number: 1,
        selectMaterialsLable: "",
        selectMaterialsValue: "",
        price: '',
        unitPrice: '',
        image: [],
        seletctMaterialsStatus: false,
        currentIndex: 0
      }
      let materialVoList = detail.materialVoList
      let code = detail.code
      let memo = detail.memo
      let cityName = detail.cityName
      let cityCode = detail.cityCode
      let currentV = {}
      currentV.v = detail.projectName
      currentV.key = detail.projectCode
      let billPicture = detail.paymentList.map(v => {
        return {
          url: v.url,
          type: v.type,
          fileType: v.source
        }
      })
      let inventoryPicture = detail.detailedList.map(v => {
        return {
          url: v.url,
          type: v.type,
          fileType: v.source
        }
      })
      materialVoList.forEach((v, i) => {
        let transition = JSON.stringify(pro)
        let transitionSuccess = JSON.parse(transition)
        transitionSuccess.selectMaterialsLable = v.materialName
        transitionSuccess.selectMaterialsValue = v.materialCode
        transitionSuccess.number = v.materialNum
        transitionSuccess.price = parseFloat(v.materialAmout)
        transitionSuccess.unitPrice = parseFloat(v.materialAmout) / parseFloat(v.materialNum)
        taskNumber.push(transitionSuccess)
      })
      this.setData({
        taskNumber,
        memo,
        inventoryPicture,
        billPicture,
        currentV,
        code,
        cityName,
        cityCode,

      })
      this.sumPrice()
    }
    if (userId) {
      this.setData({
        userId
      })
    } else {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
    this.getMaterials('')
    this.getProject('')
  },
  //打开城市选择弹窗
  openCity() {
    this.setData({
      showCity: true
    })
  },
  //关闭城市选择弹窗
  closeCity() {
    this.setData({
      showCity: false,
    })
  },
  confirmCity(e) {
    console.log(e, 'ee');

    this.setData({
      cityCode: e.detail.values[1].code,
      cityName: e.detail.values[1].name,
      showCity: false
    })
  },


})